﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

namespace Gollie.Payment.Targetpay
{
	public class IDealFetch : IDeal
	{
		string transactionId;
		string url;

		public IDealFetch(string description, string reportUrl, string returnUrl, string bankId, decimal amount)
			: this(false, description, reportUrl, returnUrl, bankId, amount)
		{
		}

		public IDealFetch(bool testMode, string description, string reportUrl, string returnUrl, string bankId, decimal amount)
			: base(testMode)
		{
			Dictionary<string, string> args = new Dictionary<string, string>();

			args["rtlo"] = partnerId;
			args["bank"] = bankId;
			args["description"] = description;
			args["reporturl"] = reportUrl;
			args["returnurl"] = returnUrl;
			args["amount"] = amount.ToString("#0");

			logger.Debug("Amount: {0}", args["amount"]);

			this.ProcessRequest(this.fetchUrl, args);
		}

		protected override void ProcessTargetPayResponse(string response)
		{
			if (response == null)
				throw new Exception("response is null");

			try
			{
				string returnCode = response.Substring(0, 6);
				if (returnCode != "000000")
				{
					this.LogReturnCode(returnCode);
					throw new Exception("FetchError " + returnCode);
				}
				this.transactionId = response.Substring(7, 16);
				this.url = response.Substring(24);
			}
			catch (Exception e)
			{
				throw new Exception("Response error: '" + response + "'", e);
			}

		}

		public string TransactionId
		{
			get { return this.transactionId; }
		}

		public string Url
		{
			get { return this.url; }
		}
	}
}